//  错误边界  实例
import { Button, Result } from '@arco-design/web-react';
import React from 'react';
class ErrorBoundary extends React.Component<
  object,
  { error?: Error | null; errorInfo?: React.ErrorInfo | null }
> {
  constructor(props) {
    super(props);
    this.state = { error: null, errorInfo: null };
  }

  componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
    console.log(error, errorInfo);
    if (
      error.message.includes('Loading chunk') ||
      error.message.includes('Failed to fetch')
    ) {
      this.setState({
        error: error,
        errorInfo: errorInfo,
      });
    }

    // 在这里还可以将错误消息记录到错误报告服务
  }

  render() {
    if (this.state.errorInfo) {
      // 错误路径
      return (
        <div
          style={{
            width: '100vw',
            height: '100vh',
            display: 'flex',
            alignItems: 'center',
          }}
        >
          <Result
            status="500"
            extra={[
              <Button
                key="again"
                style={{ margin: '0 16px' }}
                onClick={() => window.location.reload()}
              >
                Refresh
              </Button>,
            ]}
          ></Result>
        </div>
      );
    }

    // 正常情况下渲染子组件
    return this.props.children;
  }
}

export default ErrorBoundary;
